package com.mjk.manager.magicapi.plugin.webservice.proxy;

import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapClassLoader;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapInvcationHandler;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapProxy;
import com.mjk.manager.magicapi.plugin.webservice.model.WebServiceInfo;
import groovy.lang.GroovyClassLoader;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;

import java.lang.reflect.InvocationHandler;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class MagicWebServicePublish {
    private static HashMap<String, EndpointImpl> map = new HashMap();

    /**
     * webservice 接口发布
     */
    public static void publish(Class<?> clazz, String path, GroovyClassLoader groovyClassLoader, WebServiceInfo entity) {
        if (!path.startsWith(BeeCommonConstns.BACKS_LASH)) {
            path = BeeCommonConstns.BACKS_LASH + path;
        }
        Object proxy = MagicWebServiceProxy.newProxyInstance(new Class[]{clazz}, groovyClassLoader, entity);
        //是否是重启
        boolean isRestart = doPublish(path, proxy);
        //重新发布
        if (!isRestart) {
            doPublish(path, proxy);
        }
    }

    public static boolean doPublish(String path, Object proxy) {
        SpringBus bus = BeeSpringBean.getBean(SpringBus.class);
        if (map.containsKey(path)) {
            map.get(path).stop();
        }
        EndpointImpl endpoint = new EndpointImpl(bus, proxy);
        endpoint.publish(path);
        map.put(path, endpoint);
        return true;

    }
}
